(function() {
    "use strict";

    /**
     * @ngdoc function
     * @name webApp.controller:StoreCtrl
     * @description
     * # StoreCtrl
     * Controller of the webApp
     */
    angular.module("webApp").controller("StoreCtrl", StoreCtrl);

    StoreCtrl.$inject = [
        "$scope",
        "$rootScope",
        "$state",
        "dataService",
        "$location",
        "helper",
        "$timeout",
        "sessionService",
        "cacheService",
        "ERP_CONFIG",
        "$compile",
        "moment",
        "base64"
    ];

    function StoreCtrl(
        $scope,
        $rootScope,
        $state,
        dataService,
        $location,
        helper,
        $timeout,
        sessionService,
        cacheService,
        ERP_CONFIG,
        $compile,
        moment,
        base64
    ) {
        $scope.BackAppId = ERP_CONFIG.BackAppId;
        $scope.addSubStoreDoc = ERP_CONFIG.api2Url + "/upload/doc/开通多门店的操作教程.docx";
        $scope.listAction = function() {
            var token = sessionService.get("tokenUser");
            console.error("token", token);
            $scope.CompanyId = token.CompanyId;
            $scope.wxqrcodeScene = "KSAS" + $scope.CompanyId;
            $scope.getstoreList();
            $scope.$on("event:up-store-id", function() {
                $scope.getstoreList();
            });
            $scope.getZfTitle();
        };

        //授权网址
        $scope.authUrl = function() {
            return dataService.authorizePreAuthCodeGet().then(function(result) {
                $scope.isvappid = ERP_CONFIG.IsvAppID;
                if (!result.pre_auth_code) {
                    helper.myAlert("错误：" + result.Msg + "。请联系客服解决！");
                } else {
                    $scope.preCode = result.pre_auth_code;
                    var backUrl = encodeURIComponent(
                        $location.$$absUrl
                        .split("#")[0]
                        .replace("/admin.html", "/clear.html") +
                        "#?store_id=" +
                        $scope.store_id
                    );
                    $scope.appAuthUrl =
                        "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" +
                        ERP_CONFIG.IsvAppID +
                        "&pre_auth_code=" +
                        $scope.preCode +
                        "&redirect_uri=" +
                        backUrl;
                    return $scope.appAuthUrl;
                }
            });
        };

        //获取app最后1次的审核状态
        function getAppLatestAuditStatus() {
            dataService.getLatestAuditStatus($scope.wxappid).then(function(result) {
                console.error("result...", result);
                $scope.storeCurrentCodeStatus = result;
            });
        }

        //公众号关联小程序
        $scope.attachMiniapp = function() {
            $scope.wxappid = $location.search()["wxappid"]; //公众号appid
            $scope.store_id = $location.search()["store_id"];
            $scope.wxappname = $location.search()["wxappname"];
            $scope.attachedapps = [];
            gzhWxopenWxamplink();
        };

        //获取公众号关联的小程序
        function gzhWxopenWxamplink() {
            dataService.gzhWxopenWxamplink($scope.wxappid).then(function(a) {
                $scope.attachedapps = a;
                allAuthrizeAppGet(true).then(function() {
                    // console.error("111111", $scope.attachedapps, $scope.allauthrizedApp)
                    //已授权的名字数组
                    var authrizedName = _.pluck($scope.attachedapps, "nickname");
                    var storeAppName = _.pluck($scope.allauthrizedApp, "nick_name");
                    //交集
                    var jiaoji = _.intersection(authrizedName, storeAppName);
                    //没有授权公众号的app
                    $scope.noauthapp = _.difference(storeAppName, jiaoji);
                    // console.error("1111", authrizedName, storeAppName, jiaoji, $scope.noauthapp);
                });
            });
        }

        //是否没有授权
        $scope.ifAuthrized = function(nickname) {
            return $scope.noauthapp.indexOf(nickname) != -1 ? true : false;
        };

        //关联公众号
        $scope.linkApp = function(appid) {
            helper.myConfirm(
                "确认关联？需要管理员微信确认后才生效。确认后所有粉丝会收到已关联小程序的消息通知，并且展示在公众号资料中。",
                function() {
                    dataService.gzhLinkApp($scope.wxappid, appid).then(function(a) {
                        if (a) {
                            helper.myAlert("关联成功");
                            gzhWxopenWxamplink();
                        }
                    });
                }
            );
        };

        //接触关联公众号
        $scope.unlinkApp = function(appid) {
            helper.myConfirm("确认解除？", function() {
                dataService.gzhUnLinkApp($scope.wxappid, appid).then(function(a) {
                    if (a) {
                        helper.myAlert("解除成功");
                        gzhWxopenWxamplink();
                    }
                });
            });
        };

        //所有授权进来的小程序
        function allAuthrizeAppGet(nocache) {
            return dataService
                .sellerAuthorizeAuthorizer_infoGet($scope.store_id, 2, nocache)
                .then(function(result) {
                    $scope.allauthrizedApp = result;
                });
        }

        //发布小程序
        $scope.testerAction = function() {
            $scope.wxappid = $location.search()["appid"];
            $scope.store_id = $location.search()["store_id"];
            getStore();
            currentAuthrizeApp();
            getTesterList();
        };

        //获取已设置的体验者
        function getTesterList() {
            dataService.testerGet($scope.wxappid).then(function(a) {
                if (a) {
                    $scope.testers = a.value;
                } else {
                    $scope.testers = [];
                }
            });
        }
        //
        $scope.addresCallback = function(data, store) {
            $timeout(function() {
                console.error("data", data.localtion, store);
                if (data.address) {
                    $scope.store.address = data.address;
                    $scope.store.longitude = data.localtion.lng;
                    $scope.store.latitude = data.localtion.lat;
                    console.error($scope.store);
                }
            });
        }

        //添加体验者
        $scope.addTester = function(wxid) {
            if (!wxid) {
                return helper.myAlert("微信账号不能为空！");
            }
            dataService.isvTesterAdd($scope.wxappid, wxid).then(function(result) {
                if (result === true) {
                    helper.myAlert("设置成功！");
                    getTesterList();
                }
            });
        };

        //添加体验者
        $scope.deleteTester = function(wxid) {
            dataService.isvTesterDelete($scope.wxappid, wxid).then(function(result) {
                if (result === true) {
                    helper.myAlert("删除成功！");
                    getTesterList();
                } else {
                    helper.myAlert("error" + result.Msg);
                }
            });
        };

        //修改合法域名
        $scope.domainUpdate = function() {
            return dataService
                .domainUpdate(
                    $scope.wxappid,
                    "set",
                    ERP_CONFIG.requestdomain,
                    ERP_CONFIG.wsrequestdomain,
                    ERP_CONFIG.uploaddomain,
                    ERP_CONFIG.downloaddomain
                )
                .then(function(r) {
                    // console.log("domainUpdate:", r);
                    if (r.Msg) {
                        // var msg = JSON.parse(r.Msg);
                        // console.error("msg:", msg);

                        helper.myAlert(r.Msg);

                        if (r.Msg.indexOf("40001")) {
                            //$scope.authUrl();
                            return dataService.reject();
                        }
                    }
                    getStoreCurrentCodeStatus();
                    return r;
                });
        };

        $scope.setTabBarSetting = function(settings) {
            console.error("settings ", settings);
        };

        //获取小程序配置
        function xcxConfig() {
            return dataService.xcxAppJson().then(function(conf) {
                $scope.xcxAppConfig = conf;
            });
        }
        $scope.addExpressAppid = function() {
                //检测 有没有快递100的id
                if ($scope.windowConfig.navigateToMiniProgramAppIdList.indexOf('wx6885acbedba59c14') == '-1') {
                    $scope.windowConfig.navigateToMiniProgramAppIdList.push('wx6885acbedba59c14');
                }
                if ($scope.windowConfig.navigateToMiniProgramAppIdList.indexOf('wx6ed1ad00cb86dc8c') == '-1') {
                    $scope.windowConfig.navigateToMiniProgramAppIdList.push('wx6ed1ad00cb86dc8c');
                }
            }
            //s上传代码
        $scope.upload = function(templet) {
            $scope.addExpressAppid();
            console.error("templet.....", templet, $scope.windowConfig);
            var keyName = "WXAPP_UI_CONFIG_" + $scope.wxappid;
            dataService.shopConfigOneByKey(keyName)
                .then(function(a) {
                    if (a) {
                        a.value = $scope.windowConfig;
                        return dataService.shopConfigUpdate(a);
                    } else {
                        return dataService.shopConfigAdd({
                            field: keyName,
                            value: $scope.windowConfig
                        });
                    }
                })
                .then(function() {
                    //执行上传代码
                    $scope.wxappUploadOrSubmitOrRelease(templet, "upload");
                });

            // $scope.domainUpdate().then(function(r) {
            //     if (r.Msg) {
            //         helper.myAlert("出错：", r.Msg);
            //         return;
            //     }
            //     if ($scope.currentWxapp.nick_name == "大黄蜂小l程序") {
            //         $scope.currentWxapp.nick_name = "大黄蜂小程序";
            //     }

            //     var page_list = $scope.xcxAppConfig.pages;
            //     //                 console.log("---------页面", page_list);

            //     var extConfig = {
            //         "extEnable": true,
            //         "extAppid": $scope.wxappid,
            //         "ext": {
            //             "is_backend": false,
            //             "wxappname": $scope.currentWxapp.nick_name,
            //             "wxappid": $scope.wxappid,
            //             "wxapptype": $scope.currentWxapp.principal_name === "个人" ? "c" : "b",
            //             "store_id": $scope.store_id,
            //             "dhfPath": "https://api.dhfapp.com",
            //             "attachUrl": "https://img.dhfapp.com",
            //             "is_dev_mod": false,
            //             "template_id": templet.template_id,
            //             "version": templet.version,
            //         },
            //     }

            //     extConfig.tabBar = $scope.windowConfig.tabBar;
            //     extConfig.tabBarUrls = _.pluck($scope.windowConfig.tabBar.list, 'pagePath');

            //     //把tabbar的url设置到pages的头部
            //     extConfig.pages = _.union(extConfig.tabBarUrls, page_list);

            //     extConfig.window = $scope.windowConfig.topBar;
            //     //                 console.error("appUI最终配置：", extConfig)
            //     // return;

            //     var adddata = {
            //         app_id: $scope.wxappid,
            //         types: "dhfshop",
            //         template_id: templet.template_id,
            //         version: templet.version,
            //         description: "上传成功",
            //         is_uploaded: "2",
            //         upload_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            //         store_id: $scope.store_id
            //     };

            //     dataService.isvCodeCommitAdd($scope.store_id, $scope.wxappid, templet.template_id, extConfig, templet.version, templet.description).then(function(result) {
            //         if (result) {
            //             dataService.userappAdd(adddata).then(function(re) {
            //                 //展示二维码
            //                 $scope.testQrCode();

            //                 getStoreCurrentCodeStatus();
            //             });
            //         }
            //     });
            // });
        };

        //获取体验二维码
        $scope.testQrCode = function() {
            dataService.isvCodeQrcodeGet($scope.wxappid).then(function(qrimage) {
                $scope.qrimage = "data:image/png;base64," + qrimage;
                var qrcodeWin = $.alert({
                    backdrop: "static",
                    keyboard: false,
                    title: '{{"请用微信扫描体验"|translate}}',
                    body: '<p style="text-align:center"><img ng-src="{{qrimage}}" width="240" /><br><br><a href="#/store/tester?store_id={{store.store_id}}&appid={{currentWxapp.app_id}}" class="sui-btn btn-success">{{\'+体验者\'|translate}}</a></p>',
                    okBtn: '{{"关闭"|translate}}',
                    closeBtn: true,
                    hasfoot: false,
                    transition: true,
                    width: "small",
                    show: function(e) {
                        $compile($(e.currentTarget).contents())($scope);
                    },
                    okHide: function(e) {},
                    shown: function(e) {}
                });
            });
        };

        //发布小程序
        $scope.pubcodeAction = function() {
            $scope.windowConfig = {};
            $scope.wxappid = $location.search()["appid"];
            $scope.store_id = $location.search()["store_id"];
            xcxConfig().then(function() {
                getStore().then(function() {
                    currentAuthrizeApp().then(function() {
                        getStoreCurrentCodeStatus();
                    });
                });
            });
        };

        $scope.wxappUploadOrSubmitOrRelease = function(templet, type, re, ctype) {
            if (!re) {
                if (!templet) {
                    return helper.myAlert("版本号，不能为空！");
                }
            }
            var query = {
                content: {
                    app_id: $scope.wxappid,
                    store_id: $rootScope.store_id,
                    template_id: templet ? templet.template_id : "",
                    chehui: ctype ? ctype : ""
                }
            };

            var apiaty = {
                upload: "wxappUpload",
                submit: "wxappSubmit",
                release: "wxappRelease"
            };

            return dataService[apiaty[type]](query).then(function(a) {
                //console.log("111111111111",a);
                if (!a.Msg && a) {
                    if (type == "upload") {
                        if (!ctype) {
                            //展示二维码
                            $scope.testQrCode();
                        }
                    } else {
                        helper.myAlert(a.return);
                    }

                    getStoreCurrentCodeStatus();
                } else {
                    return helper.myAlert(a.Msg);
                }
            });
        };

        $scope.withdrawAndRegresses = function(type, title) {
            helper.myConfirm(title, function() {
                $scope
                    .wxappUploadOrSubmitOrRelease(
                        $scope.storeCurrentCodeStatus,
                        "upload",
                        1,
                        type
                    )
                    .then(function() {
                        getStoreCurrentCodeStatus();
                    });
            });
        };

        //代码提交审核
        $scope.codeSubmit = function(list) {
            if (!$scope.storeCurrentCodeStatus.template_id) {
                return helper.myAlert("没有已上传的版本！请先上传！");
            } else {
                $scope.wxappUploadOrSubmitOrRelease(
                    $scope.storeCurrentCodeStatus,
                    "submit"
                );
            }

            // $scope.domainUpdate().then(function() {
            //     dataService.sellerCodeGetCategoryGet($scope.wxappid).then(function(result) {
            //         if (result.code == 0) {
            //             var allcatlist = JSON.parse(result.data);
            //             allcatlist = allcatlist.category_list;
            //             // var catlist = allcatlist.category_list[0];
            //             // var tags = catlist.second_class.split("/").join(" ");

            //             //                         console.log("---------分类", allcatlist, allcatlist[0])
            //             dataService.sellerCodePageGet($scope.wxappid).then(function(page) {
            //                 if (page.code == 0) {
            //                     var page = JSON.parse(page.data);
            //                     //                                 console.log("---------页面", page);

            //                     //组件审核代码数据
            //                     var data = {
            //                         item_list: [
            //                             // {
            //                             //     "address": "page/logs/logs",
            //                             //     "tag": "学习 工作",
            //                             //     "first_class": "教育",
            //                             //     "second_class": "学历教育",
            //                             //     "third_class": "高等",
            //                             //     "title": "日志",
            //                             // }
            //                         ]
            //                     };

            //                     var xxx = 0;
            //                     var onePage;
            //                     _.map(page.page_list, function(p, i) {
            //                         //首页==========================
            //                         if (allcatlist[xxx]) {
            //                             onePage = clone(allcatlist[xxx]);
            //                             xxx++;
            //                         } else {
            //                             return;
            //                         }
            //                         onePage.address = p;
            //                         onePage.tag = onePage.second_class.replace(/\//g, " ");

            //                         if (p == "pages/index/index") {
            //                             onePage.title = "首页";
            //                         } else if (p == "pages/cat/index") {
            //                             onePage.title = "分类";
            //                         } else if (p == "pages/cart/index") {
            //                             onePage.title = "购物车";
            //                         } else {
            //                             onePage.title = "其他";
            //                         }

            //                         if (data.item_list.length < 5) {
            //                             data.item_list.push(onePage);
            //                         }

            //                     });

            //                     // console.log("-----", data)
            //                     var adddata = {
            //                         app_id: $scope.wxappid,
            //                         types: "dhfshop",
            //                         template_id: $scope.storeCurrentCodeStatus.template_id,
            //                         version: list.version,
            //                         description: "提交审核成功",
            //                         // is_uploaded: "2",
            //                         is_subaduited: "2",
            //                         subaduit_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            //                         subaduit_id: "",
            //                         store_id: $scope.store_id
            //                     };

            //                     console.error("提交审核的数据：", data);
            //                     // return;

            //                     dataService.codeSubmitAuditAdd($scope.store_id, $scope.wxappid, data, $scope.storeCurrentCodeStatus.template_id).then(function(a) {
            //                         //获取状态
            //                         if (a.auditid) {
            //                             adddata.subaduit_id = a.auditid;
            //                             dataService.userappAdd(adddata).then(function(re) {
            //                                 getStoreCurrentCodeStatus();
            //                             });
            //                         } else {
            //                             return helper.myAlert("出错：" + a.Msg);
            //                         }
            //                     });
            //                 }
            //             });
            //         }
            //     });
            // });
        };

        //获取当前已发布版本 需要新增店铺id
        function getStoreCurrentCodeStatus() {
            return dataService
                .getStoreCodeStatus($scope.store_id, $scope.wxappid)
                .then(function(a) {
                    // console.error("",a);
                    a = a || {};
                    $scope.storeCurrentCodeStatus = a;
                    return dataService
                        .getLatestAuditStatus($scope.wxappid)
                        .then(function(result) {
                            result = result || {};
                            $scope.CurrentAuditStatus = result;
                            if (a.auditid == result.auditid) {
                                $scope.storeCurrentCodeStatus.auditstatus = result.status;
                            } else {
                                $scope.CurrentAuditStatus.nocurrent = true;
                            }
                            $scope.xtotal = 0;
                            $scope.pageSize = 10;
                            $scope.getList();
                        });
                });
        }

        //发布代码
        $scope.publish = function(list) {
            $scope.wxappUploadOrSubmitOrRelease(list, "release", 1);

            // dataService.codeReleaseAdd($scope.store_id, $scope.wxappid).then(function(a) {
            //     if (a.code == 0) {
            //         if (!list) {
            //             helper.myAlert("发布成功！");
            //             return;
            //         }
            //         var adddata = {
            //             app_id: $scope.wxappid,
            //             types: "dhfshop",
            //             template_id: list.template_id || "",
            //             version: list.version || "",
            //             description: "发布成功",
            //             is_published: "2",
            //             is_passed: "2",
            //             publish_time: moment().format('YYYY-MM-DD HH:mm:ss'),
            //             store_id: $scope.store_id
            //         };
            //         dataService.userappAdd(adddata).then(function(re) {
            //             getStoreCurrentCodeStatus();
            //         });
            //     } else {
            //         helper.myAlert(a.errmsg);
            //     }
            // });
        };

        //可见性
        $scope.visible = function(action) {
            helper.myAlert("没写！！！");
        };

        //获取代码版本
        $scope.getList = function(pageNo) {
            $scope.pageNo = pageNo || 1;
            var query = {
                query: {},
                page_no: $scope.pageNo,
                page_size: $scope.pageSize
            };

            if ($scope.wxappid) {
                query.query.app_id = $scope.wxappid;
            }
            // return dataService.isvWxappGet(query).then(function(list) {
            //     console.error("listlistlist", list);
            //     if (list && list.wxapps) {
            //         $scope.wxapps = list.wxapps;
            //         $scope.xtotal = list.total_count;
            //     }
            // });

            return dataService.userappGet(query).then(function(list) {
                if (list && list.user_apps) {
                    _.map(list.user_apps, function(da) {
                        if (da.publish_time == "0001-01-01 00:00:00") {
                            da.publish_time = "";
                        }
                        if (da.subaduit_time == "0001-01-01 00:00:00") {
                            da.subaduit_time = "";
                        }
                    });
                    $scope.wxapps = list.user_apps;
                    $scope.xtotal = list.total_count;
                }
            });
        };

        function getStore() {
            $scope.store_id = $location.search()["store_id"];
            if (!$scope.store_id) {
                return helper.myAlert("非法门店id", "#/store/list");
            } else {
                return dataService.storeOne($scope.store_id).then(function(store) {
                    // console.log("...........................------", store)
                    if (!store.store_id) {
                        return helper.myAlert("非法门店", "#/store/list");
                    } else {
                        $scope.store = store;
                        return;
                    }
                });
            }
        }

        //得到授权
        $scope.configAction = function() {
            var auth_code = $location.search()["auth_code"];
            $scope.store_id = $location.search()["store_id"];
            $scope.idtype = 1;
            $scope.idtypes = 1;
            $scope.chosedApps = [];
            $scope.Status = "guanlian";
            // $scope.saveplatform(690);
            getStore()
                .then(authrizeAppGet(true))
                .then($scope.getAllauthrizeApp);
        };

        $scope.checkAll = function(type) {
            if (!type) {
                if ($scope.idtype) {
                    $scope.chosedApps = clone($scope.storeAppList);
                    $scope.idtype = 0;
                } else {
                    $scope.chosedApps = [];
                    $scope.idtype = 1;
                }
            } else {
                if ($scope.idtypes) {
                    $scope.reomApps = clone($scope.authrizeApp);
                    $scope.idtypes = 0;
                } else {
                    $scope.reomApps = [];
                    $scope.idtypes = 1;
                }
            }
        };
        //切换tab
        $scope.switchtab = function() {
            $scope.chosedApps = $scope.reomApps = [];
            $scope.idtype = $scope.idtypes = 1;
            authrizeAppGet(true).then($scope.getAllauthrizeApp);
        };

        //将选择的授权数据保存数据库
        $scope.storeappadd = function($event, type) {
            if (!$scope.chosedApps || !$scope.reomApps) {
                helper.myAlert("请选择授权小程序");
                return false;
            }
            var title = type ?
                "确认后，选中的小程序全部取消店铺授权？" :
                "确认后，选中的小程序全部授权到店铺中？";

            var caozdata = type ? $scope.reomApps : $scope.chosedApps;

            helper.myConfirm(title, function() {
                helper.myTip("操作中,请勿操作!", $event.currentTarget, null, 10);
                var dd = 0;
                async.map(
                    caozdata,
                    function(data, callback) {
                        if (data) {
                            $scope.data = clone(data);
                            if (type) {
                                $scope.delStoreApp().then(function(r) {
                                    callback(r, null);
                                });
                            } else {
                                $scope.saveStoreApp().then(function(r) {
                                    callback(r, null);
                                });
                            }
                            // console.error("$scope.fhmoder", data);
                        } else {
                            callback(null);
                        }
                    },
                    function(e, r) {
                        // console.error("ee", e, r);
                        if (e) {
                            helper.myAlert("success", null, null, function() {
                                $scope.switchtab();
                                dataService.removeDataCache();
                            });
                        }
                    }
                );
            });
        };

        $scope.saveStoreApp = function() {
            var Adddata = {
                content: {
                    app_id: $scope.data.app_id,
                    store_id: $rootScope.store_id,
                    partner_id: $scope.data.partner_id
                }
            };
            return dataService.storeAppAdd(Adddata).then(function(retu) {
                if (retu.Msg) {
                    helper.myAlert("error" + retu.Msg);
                    return false;
                } else {
                    return true;
                }
            });
        };
        $scope.delStoreApp = function() {
            var deldata = {
                content: {
                    store_apps_id: $scope.data.store_apps_id
                }
            };

            return dataService.storeAppDel(deldata).then(function(retu) {
                if (retu.Msg) {
                    return false;
                } else {
                    return true;
                }
            });
        };
        //读取所有 小程序 授权 未授权的
        $scope.getAllauthrizeApp = function() {
            var datas = {
                // page_no: pageNo ? pageNo : 1,
                // page_size: $scope.pageSize ? $scope.pageSize : 10,
            };

            return dataService.storeAppAllGet(datas).then(function(result) {
                var isresult = aryBobj(result);
                var applist = aryBobj($scope.authrizeApp);
                _.map(applist, function(isda, iske) {
                    if (isresult[iske]) {
                        delete isresult[iske];
                    }
                });
                $scope.storeAppList = objBary(isresult);
                // console.error(" $scope.storeAppList", $scope.storeAppList);
            });
        };

        function aryBobj(isresult) {
            var data = {};
            _.map(isresult, function(da, ke) {
                data[da.app_id] = da;
            });
            return data;
        }

        function objBary(isresult) {
            var data = [];
            _.map(isresult, function(da, ke) {
                data.push(da);
            });
            return data;
        }
        //保存授权
        $scope.saveAuth = function(data) {
            console.error("saveAuth callback:", data, ERP_CONFIG.IsvAppID);
            if (data.auth_code) {
                dataService
                    .authorizeAuthCodeGet(
                        ERP_CONFIG.IsvAppID,
                        data.auth_code,
                        data.store_id
                    )
                    .then(function(result) {
                        console.log("授权保存结果：", result);
                        if (result.Msg) {
                            helper.myAlert("错误：" + result.Msg);
                        } else {
                            // $scope.saveplatform(result.cust_account_id);
                            helper.myAlert("授权成功！");
                            authrizeAppGet(true);
                            // newauthrizeAppGet();
                        }
                    });
            } else {
                helper.myAlert("授权出错，请重试！");
            }
        };

        //查询 平台绑定关系
        $scope.wxCgibinOpenGet = function() {
            var data = {
                appid: $scope.app_id
            };
            dataService.wxCgibinOpenGet($scope.app_id, data).then(function(result) {
                console.log("查询结果：", result);
                if (result.errcode == 89002) {
                    $scope.open_appid = "";
                    // $scope.getAppPlatformInfo();
                    //去进行绑定 一个平台 可以绑定多个小程序
                }
                if (result.errcode == 0) {
                    $scope.wcplatform = result;
                    $scope.open_appid = result.open_appid;
                    if (!$scope.platformlists) {
                        $scope.saveappPlatform($scope.open_appid);
                    }
                }
            });
        };

        $scope.rmAppPlatform = function() {
            var data = {
                app_id: $scope.app_id,
                open_appid: $scope.open_appid
            };
            dataService.rmAppPlatform(data).then(function(result) {
                console.log("结果：", result);
                //添加数据
                if (!result.Msg) {
                    $scope.getPlatform();
                    $scope.wxCgibinOpenGet();
                    helper.myAlert("解除绑定成功！");
                } else {
                    helper.myAlert(result.Msg);
                }
            });
        };

        //保存数据库
        $scope.saveappPlatform = function(open_appid, type) {
            var data = {
                app_id: $scope.app_id,
                open_appid: open_appid,
                principal_name: $scope.principal_name
            };
            if (!$scope.platformlists) {
                data.type = "add";
            }
            dataService.addAppPlatform(data).then(function(result) {
                if (result.open_appid) {
                    if (type) {
                        helper.myAlert("绑定成功！");
                        $scope.platformAction();
                    }
                    $scope.getPlatform();
                }
            });
        };

        //绑定平台
        $scope.platformAction = function() {
            $scope.app_id = $location.search().app_id;
            var data = {
                content: {
                    app_id: $scope.app_id
                }
            };
            dataService.getCustaccount(data).then(function(result) {
                if (!result.Msg) {
                    $scope.wxappDatd = result;
                    $scope.principal_name = $scope.wxappDatd.principal_name;
                    $scope.getPlatform();
                    $scope.wxCgibinOpenGet();
                }
            });
            //1 去查询 绑定平台 有的话，展示出绑定的数据 。然后在查询数据库中，有没有数据 没有进行添加
        };
        $scope.getPlatform = function() {
            var data = {
                principal_name: $scope.principal_name,
                app_id: $scope.app_id
            };
            $scope.Msg = "";
            $scope.platformlists = "";
            dataService.getPlatformInfo(data).then(function(result) {
                if (result.data && result.data != null) {
                    $scope.platformlists = result.data;
                }
            });
        };

        //保存门店关系 append=true 追加门店
        $scope.setAppStore = function(app_id, store_id, append) {
            var keyName = "CONFIG-STORES";

            function stores(v, store_id) {
                if (v && append) {
                    v = JSON.parse(v);
                } else {
                    v = [];
                }

                v.push(store_id);
                v = _.uniq(v);
                return v;
            }
            var data = {
                appid: app_id,
                cid: 0,
                name: keyName
            };

            return dataService.wxappOne(data).then(function(config) {
                if (config) {
                    config.value = stores(config.value, store_id);
                } else {
                    config = {
                        store_id: store_id,
                        app_id: app_id,
                        name: "CONFIG-STORES",
                        value: stores("", store_id),
                        types: "config"
                    };
                }

                console.error("config:", config);

                var method = config.wxapp_cfg_id ? "wxappUpdate" : "wxappAdd";
                return dataService[method](config).then(function(result) {
                    if (result.app_id) {
                        helper.myAlert("成功！");
                        return true;
                    } else {
                        helper.myAlert("出错：" + result.Msg);
                        return false;
                    }
                });
            });
        };

        //弹出小程序二维码;
        $scope.openQrcode = function(app_id) {
            wxappQrcode(app_id).then(function(image) {
                console.error("二维码数据：", image);
                if (!image) {
                    //$scope.authUrl();
                    helper.myAlert("出错了！");
                    return false;
                }

                $.alert({
                    backdrop: "static",
                    keyboard: false,
                    title: "<span>小程序二维码，请使用微信扫描</span>",
                    body: '<div style="text-align:center;"><img src="data:image/png;base64,' +
                        image +
                        '"  width="240"/></div>',
                    okBtn: '{{"二维码"|translate}}',
                    closeBtn: true,
                    hasfoot: false,
                    transition: true,
                    width: "small",
                    show: function(e) {},
                    okHide: function(e) {},
                    shown: function(e) {}
                });
            });
        };

        //小程序二维码
        function wxappQrcode(wxappid) {
            return dataService
                .acodeunlimitGet(
                    wxappid,
                    "S" + $rootScope.store_id,
                    true,
                    "pages/index/index"
                )
                .then(function(r) {
                    return r;
                });
        }

        //读取授权app信息
        function authrizeAppGet(nocache) {
            return dataService
                .sellerAuthorizeAuthorizer_infoGet($scope.store_id, null, nocache)
                .then(function(result) {
                    $scope.authrizeApp = result;
                });
        }

        function initTopBar() {
            return {
                navigationBarBackgroundColor: "#ffffff",
                navigationBarTextStyle: "black",
                navigationBarTitleText: "首页",
                backgroundColor: "#f8f8f8",
                backgroundTextStyle: "dark"
            };
        }

        function initTabBar() {
            if ($scope.store.industry_code == 5) {
                return {
                    color: "#999999",
                    selectedColor: "#2c84ff",
                    borderStyle: "#f3f3f3",
                    backgroundColor: "#fff",
                    list: [{
                            pagePath: "pages/ministore/get/index",
                            iconPath: "assets/images/home999999.png",
                            selectedIconPath: "assets/images/home3388FF.png",
                            text: "附近的师傅"
                        },
                        {
                            pagePath: "pages/ministore/add/index",
                            iconPath: "assets/images/my999999.png",
                            selectedIconPath: "assets/images/my3388FF.png",
                            text: "我是师傅"
                        }
                    ]
                };
            } else if (
                $scope.currentWxapp &&
                $scope.currentWxapp.principal_name === "个人"
            ) {
                return {
                    color: "#999999",
                    selectedColor: "#2c84ff",
                    borderStyle: "#f3f3f3",
                    backgroundColor: "#fff",
                    list: [{
                            pagePath: "pages/index/index",
                            iconPath: "assets/images/home999999.png",
                            selectedIconPath: "assets/images/home3388FF.png",
                            text: "首页"
                        },
                        {
                            pagePath: "pages/user/index",
                            iconPath: "assets/images/my999999.png",
                            selectedIconPath: "assets/images/my3388FF.png",
                            text: "我的"
                        }
                    ]
                };
            } else {
                return {
                    color: "#999999",
                    selectedColor: "#2c84ff",
                    borderStyle: "#f3f3f3",
                    backgroundColor: "#fff",
                    list: [{
                            pagePath: "pages/index/index",
                            iconPath: "assets/images/home999999.png",
                            selectedIconPath: "assets/images/home3388FF.png",
                            text: "首页"
                        },
                        {
                            pagePath: "pages/cart/index",
                            iconPath: "assets/images/cart999999.png",
                            selectedIconPath: "assets/images/cart3388FF.png",
                            text: "购物车"
                        },
                        {
                            pagePath: "pages/order/list/index",
                            iconPath: "assets/images/order999999.png",
                            selectedIconPath: "assets/images/order3388FF.png",
                            text: "订单"
                        },
                        {
                            pagePath: "pages/user/index",
                            iconPath: "assets/images/my999999.png",
                            selectedIconPath: "assets/images/my3388FF.png",
                            text: "我的"
                        }
                    ]
                };
            }
        }
        $scope.currentAuthrizeApp = function() {
            currentAuthrizeApp();
        };
        //获取单个授权wxapp信息
        function currentAuthrizeApp() {
            return dataService
                .wxappAuthorizerOne($scope.store_id, $scope.wxappid)
                .then(function(a) {
                    //console.log("$scope.currentWxapp", a);
                    $scope.currentWxapp = a;

                    $scope.windowConfig = {};
                    //顶部栏
                    return dataService
                        .shopConfigOneByKey("WXAPP_UI_CONFIG_" + $scope.wxappid)
                        .then(function(conf) {
                            $timeout(function() {
                                var itopBar = initTopBar();
                                var itabBar = initTabBar();
                                //                         console.error("默认tabBar配置：", itabBar);
                                if (conf) {
                                    if (conf.value) {
                                        $scope.windowConfig = JSON.parse(conf.value);
                                    } else {
                                        $scope.windowConfig.topBar = itopBar;
                                        $scope.windowConfig.tabBar = itabBar;
                                    }
                                    /*
                                              //                             console.error("上次的app配置：", $scope.windowConfig);
                                              for (var i in $scope.windowConfig.tabBar.list) {
                                                  if ($scope.windowConfig.tabBar.list[i].pagePath != itabBar.list[i].pagePath) {
                                                      $scope.windowConfig.topBar = itopBar;
                                                      $scope.windowConfig.tabBar = itabBar;
                                                      break;
                                                  }
                                              }
                                              */
                                } else {
                                    $scope.windowConfig.topBar = itopBar;
                                    $scope.windowConfig.tabBar = itabBar;
                                }
                                //                         console.error("初始化得到的 WXAPP_UI_CONFIG:", $scope.windowConfig);
                            });
                        });
                });
        }

        //获取store列表
        $scope.getstoreList = function(pageNo) {
            $scope.partner_id = dataService.currentLoginedUser().partner_id;
            var query = {
                page_no: 1,
                page_size: 10,
                query: {
                    store_id: $rootScope.store_id
                }
            };
            // $scope.addMultilStoreWhiteList();
            dataService.storeGet(query).then(function(list) {
                if (list && list.total_count) {
                    $scope.storeList = list.store;
                    $scope.storeTotal = list.total_count;
                    $scope.partner_id = list.store[0].partner_id;
                    $scope.addMultilStoreWhiteList();
                }
            });
        };

        //添加
        $scope.addAction = function() {
            $scope.getstoreList();
            var store_id = $location.search().store_id;
            if (store_id) {
                dataService.storeOne(store_id).then(function(retun) {
                    if (retun) {
                        $scope.oldstore = retun;
                        if (retun.config) {
                            $scope.oldstore.config = JSON.parse(retun.config);
                        }
                        $scope.store = clone($scope.oldstore);
                    }
                });
            } else {
                $scope.store = {
                    // name: "赵四",
                    // address: "北京北京市朝阳区四惠东区110号大院",
                    // phone: "18611112222",
                };
            }
        };
        /*****
                多门店白名单
                ******/
        $scope.addMultilStoreWhiteList = function(partner_id) {
            var xlist = ERP_CONFIG.addStoreWhiteList;
            $scope.showAddStore =
                xlist.indexOf($scope.partner_id) != -1 ? true : false;
            // console.error("白名单==", $scope.showAddStore, "所以白名单列表==", xlist);
        };

        $scope.getwxapplist = function() {
            dataService.WxGettemplatedraftlist(ERP_CONFIG.BackAppId).then(function(result) {
                console.error("result", result);
            });
        }

        //回调方法
        $scope.wxaacallback = function(id) {
            if (id) {
                $scope.wxappid = id;
                $scope.getlist();
            }
        }

        $scope.storeAdd = function() {
            if ($scope.store) {
                if ($scope.store.store_id) {
                    var data = clone($scope.store);
                    //config有数据的话，则需要格式化
                    if (data.config) {
                        //判断role_id app_id
                        if (!$scope.store.config.store_apply.role_id || !$scope.store.config.store_apply.app_id) {
                            helper.message("角色或者APPID没有填写，无法保存店铺数据", "error");
                            return false;
                        }
                        data.config = JSON.stringify(data.config);
                    }
                    console.error("data", data);
                    // return false;
                    if (data.is_main == $scope.oldstore.is_main) {
                        delete data.is_main;
                    }
                    // if($scope.store.is_main == 1)
                    // {
                    //     //判断role_id app_id
                    //     if(!$scope.store.config.store_apply.role_id || !$scope.store.config.store_apply.app_id){
                    //         helper.message("角色或者APPID没有填写，无法保存店铺数据","error");
                    //         return false;
                    //     }
                    // }
                    dataService.storeUp(data).then(function(re) {
                        if (re.store_id) {
                            $rootScope.$broadcast("event:store-update");
                            helper.myAlert("success", "#/store/list");
                        } else {
                            helper.myAlert(re.Msg);
                        }
                    });
                } else {
                    dataService.storeAdd($scope.store).then(function(re) {
                        if (re.store_id) {
                            $rootScope.$broadcast("event:store-update");
                            helper.myAlert("success", "#/store/list");
                        } else {
                            helper.myAlert(re.Msg);
                        }
                    });


                }
            } else {
                helper.myAlert("store数据不存在！");
            }
        };

        //设置支付配置参数Action
        $scope.payConfigAction = function() {
            $scope.cust_account_id = Number($location.search().cust_account_id);
            $scope.appid = $location.search().appid;

            $scope.store_id = $location.search().store_id;

            if (!$scope.store_id || !$scope.cust_account_id) {
                return helper.myAlert("非法门店id", "#/store/list");
            } else {
                dataService.storeOne($scope.store_id).then(function(retun) {
                    if (retun) {
                        $scope.store = retun;
                    }
                });

                $scope.wxappid = $location.search().appid;
                currentAuthrizeApp();

                dataService.payConfigGet($scope.cust_account_id).then(function(result) {
                    if (result) {
                        if (result.media_id) {
                            $scope.updateType = 1;
                        } else {
                            $scope.updateType = 0;
                        }
                        $scope.payconfig = result;
                    } else {
                        $scope.payconfig = {
                            mch_type_id: 2,
                            cust_account_id: $scope.cust_account_id
                        };
                    }
                });
            }
        };

        $scope.payConfigAdd = function() {
            $scope.payconfig.mch_id = $scope.payconfig.mch_type_id == 2 ? 1394024102 : $scope.payconfig.mch_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 3 ? 1 : 2;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 4 ? 9 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 5 ? 10 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 6 ? 13 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 8 ? 12 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 9 ? 14 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 10 ? 16 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 11 ? 15 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 12 ? 17 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 13 ? 18 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 14 ? 20 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 15 ? 22 : $scope.payconfig.pay_way_id;
            $scope.payconfig.pay_way_id = $scope.payconfig.mch_type_id == 16 ? 23 : $scope.payconfig.pay_way_id;

            $scope.payconfig.app_id = $scope.payconfig.mch_type_id == 2 ? ERP_CONFIG.BackGzhId : $scope.appid;
            $scope.payconfig.sub_app_id = $scope.appid;
            // $scope.payconfig.app_id = "wx82bd84ec09fed74e"
            // $scope.payconfig.sub_app_id = "wx979a17eece0bcf22"

            if (!$scope.payconfig.name && $scope.payconfig.pay_way_id < 9) {
                helper.myAlert("支付商户名称必须填写");
                return;
            }
            if (!$scope.payconfig.appkey && $scope.payconfig.pay_way_id < 9) {
                helper.myAlert("支付appkey称必须填写");
                return;
            }

            //特约删除，只需要入参子商户号
            if ($scope.payconfig.mch_type_id == 2) {
                $scope.payconfig.pem_cert = "";
                $scope.payconfig.pem_key = "";
                if (!$scope.payconfig.sub_mch_id) {
                    helper.myAlert("子商户号必须填写");
                    return;
                }
            }
            if (($scope.payconfig.mch_type_id == 14 || $scope.payconfig.mch_type_id == 15 || $scope.payconfig.mch_type_id == 1) && $scope.payconfig.mch_id && ($scope.payconfig.mch_id != $scope.payconfig.sub_mch_id)) {
                $scope.payconfig.mch_id = $scope.payconfig.sub_mch_id;
            }
            if (!$scope.payconfig.mch_id) {
                $scope.payconfig.mch_id = $scope.payconfig.sub_mch_id;
            }
            // return str.contains(substr);
            // if ($scope.payconfig.pem_cert) {
            //     if ($scope.payconfig.pem_cert.indexOf("-----BEGIN CERTIFICATE-----") < 0) {
            //         helper.myAlert("支付证书公钥文件，上传失败！,请上传apiclient_cert.pem文件");
            //         return false;
            //     }
            // }

            // if ($scope.payconfig.pem_key) {
            //     if ($scope.payconfig.pem_key.indexOf("-----BEGIN PRIVATE KEY-----") < 0) {
            //         helper.myAlert("支付证书私钥文件，上传失败！,请上传apiclient_key.pem文件");
            //         return false;
            //     }

            // }

            if ($scope.payconfig.pay_params_id) {
                dataService.payConfigUpdate($scope.payconfig).then(function(result) {
                    if (result.pay_params_id) {
                        helper.myAlert(
                            "success",
                            "#/store/config?store_id=" + $scope.store_id
                        );
                    }
                });
            } else {
                dataService.payConfigAdd($scope.payconfig).then(function(result) {
                    if (result.pay_params_id) {
                        helper.myAlert(
                            "success",
                            "#/store/config?store_id=" + $scope.store_id
                        );
                    } else {
                        helper.myAlert("参数不全！");
                    }
                });
            }
        };

        $scope.payconfigValid = function() {
            $scope.payconfig = $scope.payconfig || {};
            if ($scope.payconfig.pay_way_id == 1) {
                //微信直接支付
                if (!$scope.payconfig.name ||
                    !$scope.payconfig.mch_id ||
                    !$scope.payconfig.appkey
                ) {
                    return false;
                }
            } else if ($scope.payconfig.pay_way_id == 2) {
                //特约商户支付
                if (!$scope.payconfig.sub_mch_id) {
                    return false;
                }
            } else {
                //二维码转账支付
                return false;
            }

            return true;
        };

        //设置支付配置参数Action
        $scope.addresslistAction = function() {
            $scope.store_id = $location.search().store_id;
            if (!$scope.store_id) {
                return helper.myAlert("非法门店id", "#/store/list");
            } else {


                dataService.storeOne($scope.store_id).then(function(retun) {
                    if (retun) {
                        $scope.store = retun;
                    }
                });
                $scope.app_id = $location.search().appid;
            }
        };

        //设置支付配置参数Action
        $scope.addressAction = function() {
            $scope.store_id = $location.search().store_id;
            if (!$scope.store_id) {
                return helper.myAlert("非法门店id", "#/store/list");
            } else {
                dataService.storeOne($scope.store_id).then(function(retun) {
                    if (retun) {
                        $scope.store = retun;
                    }
                });
                $scope.wxappid = $location.search().appid;
            }
        };

        $scope.addressAdd = function() {
            // console.error("$scope.address", $scope.address);
            dataService
                .wxproxy(
                    $scope.wxappid,
                    "https://api.weixin.qq.com/wxa/addnearbypoi?access_token=TOKEN",
                    "POST",
                    $scope.address
                )
                .then(function(result) {
                    // console.error("result", result);
                });
        };
        $scope.storeXcxConfig = function() {
            $scope.dsaveKey = {};
            $scope.userMenuBars = [{
                    value: "/pages/order/list/index",
                    text: "我的订单"
                },
                {
                    value: "/pages/address/list/index",
                    text: "收货地址"
                },
                {
                    value: "/pages/favorites/list/index",
                    text: "收藏商品"
                },
                {
                    value: "/pages/appointment/list/index",
                    text: "我的预约"
                },
                {
                    value: "/pages/account/detail/index",
                    text: "我的余额"
                },
                {
                    value: "/pages/distribution/add/index",
                    text: "我要代理"
                },
                {
                    value: "/pages/huodong/list/index",
                    text: "我的报名"
                },
                {
                    value: "/pages/classes/list/index",
                    text: "我的课程"
                },
                {
                    value: "/pages/order/rentOderList/index",
                    text: "酒店订单"
                },
                {
                    value: "/pages/coupon/my/index",
                    text: "我的卡券"
                },
                {
                    value: "/pages/form/diaochalist/index",
                    text: "我的表单"
                }
            ];

            $scope.countryDelivery = [{
                    value: "CN",
                    text: "中国"
                },
                {
                    value: "CNNULLGPS",
                    text: "中国（手动填写）"
                },
                {
                    value: "NL",
                    text: "荷兰"
                },
                {
                    value: "AU",
                    text: "澳洲"
                },
                {
                    value: "US",
                    text: "美国"
                },
                {
                    value: "RU",
                    text: "俄罗斯"
                },
                {
                    value: "UA",
                    text: "乌克兰"
                },
                {
                    value: "JP",
                    text: "日本"
                },
                {
                    value: "KR",
                    text: "韩国"
                },
                {
                    value: "MY",
                    text: "马来西亚"
                },
                {
                    value: "HW",
                    text: "海外"
                }
            ];
            $scope.huilvs = [{
                name: "",
                fee: 0
            }];
            $scope.shoukuanQrCode = {
                iscode: 0,
                codeStr: ""
            };
            $scope.minMoney = {
                minmoney: 0
            };
            $scope.kuaidiConfig = {
                wuliuappid: "wx6885acbedba59c14",
                wuliu: "pages/result/result?com=&querySource=xcx_huangfengkeji&nu="
            };
            $scope.config = {};

            $scope.userMenuClone = clone($scope.userMenuBars);

            var userMenuCheckedArray = _.pluck($scope.userMenuBars, "value");
            var DevliveryCountry = _.pluck($scope.countryDelivery, "value");
            $scope.storeBaseconfig("CONFIG-PAYQRCODE", $scope.shoukuanQrCode);
            $scope.storeBaseconfig("CONFIG-DELIVERY", [1, 2]);
            $scope.storeBaseconfig("CONFIG-PAYPHONEYAN", 1);
            $scope.storeBaseconfig("CONFIG-ADDRESSGPS", 0);
            $scope.storeBaseconfig("CONFIG-ISDISTRIBUTION", 1);
            $scope.storeBaseconfig("ADD_TRADE_TYPE", 1);
            $scope.storeBaseconfig("CONFIG-HUILV", $scope.huilvs);
            $scope.storeBaseconfig("CONFIG-MENUBAR", userMenuCheckedArray);
            $scope.storeBaseconfig("CONFIG-COUNTRYDELIVERY", ["CN"]);
            $scope.storeBaseconfig("CONFIG-DELIVERYFEE", 0);
            $scope.storeBaseconfig("CONFIG-BusinessHours", {
                start_time: "",
                end_time: ""
            });
            $scope.storeBaseconfig("CONFIG-BusinessHours1", {
                start_time: "",
                end_time: ""
            });
            $scope.storeBaseconfig("CONFIG-BusinessHours2", {
                start_time: "",
                end_time: ""
            });

            $scope.storeBaseconfig("CONFIG-PEISONGDATE", {
                start_time: "00:00",

                end_time: "00:00",
                date_list: []
                    // "daynum": 0,
                    // "datejiange": 15
            });

            $scope.storeBaseconfig("CONFIG-STORECONF", {
                "zitiname": "自提点",
                "fahuoname": "发货点",
                "shouhuoname": "收货地址",
                "closeItemLink": 0,
                "closeOrderAdd": 0
            })
            $scope.storeBaseconfig("CONFIG-KUAIDIGET", $scope.kuaidiConfig);
            $scope.storeBaseconfig("CONFIG-MINMONEY", $scope.minMoney);
            $scope.storeBaseconfig("CONFIG-ShowLevelPrice", 1);
            $scope.storeBaseconfig("CONFIG-FENZHANG", 0);
            $scope.storeBaseconfig("CONFIG-ORDERXIEYI", {
                title: "",
                content: "",
                isautoopen: 0
            });
            $scope.storeBaseconfig("CONFIG-FENXIAO-FENZHANG", 0);
            $scope.storeBaseconfig("CONFIG-EXCHANGE", {
                "integral": 0,
                "yuan": 0,
                "minlimit": 0,
                "xtype": 0,
                "proportion": 0,
                "isopen": 1,
            });
        };
        $scope.storeBaseconfig = function(keyName, initChckedArray) {
            $scope.store_id = $location.search()["store_id"];
            $scope.app_id = $location.search()["app_id"];

            function DELIVERYS(v, store_id) {
                if (v) {
                    v = JSON.parse(v);
                    if (!v[store_id] && v[store_id] != 0) {
                        v[store_id] = initChckedArray;
                    }
                } else {
                    v = {};
                    v[store_id] = initChckedArray;
                }
                return v;
            }
            var data = {
                appid: $scope.app_id,
                cid: 0,
                name: keyName,
                store_id: $scope.store_id
            };
            dataService.wxappOne(data).then(function(config) {
                if (config) {
                    config.value = DELIVERYS(config.value, $scope.store_id);
                } else {
                    config = {
                        store_id: $scope.store_id,
                        app_id: $scope.app_id,
                        name: keyName,
                        value: DELIVERYS("", $scope.store_id),
                        types: "config"
                    };
                    $scope.dsaveKey[keyName] = {
                        keyName: keyName,
                        saveObjKey: null,
                    }
                }
                if (keyName == "CONFIG-MENUBAR") {
                    if (_.isString(config.value[$scope.store_id][0])) {
                        $scope.userMenuChecked = config.value[$scope.store_id];
                    } else {
                        $scope.userMenuChecked = [];
                        _.map(config.value[$scope.store_id], function(menu) {
                            if (menu.value) {
                                $scope.userMenuChecked.push(menu.value);
                                var i = _.findIndex($scope.userMenuBars, {
                                    value: menu.value
                                })
                                if (i > -1) {
                                    $scope.userMenuBars[i].text = menu.text;
                                }
                            }
                        })
                    }
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'userMenuChecked'
                    }
                } else if (keyName == "CONFIG-DELIVERY") {
                    $scope.deliveryTypes = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'deliveryTypes'
                    }
                } else if (keyName == "CONFIG-PAYPHONEYAN") {
                    $scope.payphone = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'payphone'
                    }
                } else if (keyName == "CONFIG-FENZHANG") {
                    $scope.fenzhang = config.value[$scope.store_id];
                    // $scope.fenzhang = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'fenzhang'
                    }
                } else if (keyName == "CONFIG-ISDISTRIBUTION") {
                    $scope.DistributionZT = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'DistributionZT'
                    }
                } else if (keyName == "ADD_TRADE_TYPE") {
                    $scope.OrderAddSet = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'OrderAddSet'
                    }
                } else if (keyName == "CONFIG-COUNTRYDELIVERY") {
                    $scope.countryDeliveryChecked = config.value[$scope.store_id];
                    console.error(
                        "countryDeliveryChecked",
                        $scope.countryDeliveryChecked
                    );
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'countryDeliveryChecked'
                    }
                } else if (keyName == "CONFIG-DELIVERYFEE") {
                    $scope.deliveryFee = config.value[$scope.store_id];
                    $scope.stepfreightGetOne($scope.deliveryFee);
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'deliveryFee'
                    }
                    // console.error("deliveryFee", $scope.deliveryFee);
                } else if (keyName == "CONFIG-BusinessHours") {
                    $scope.BusinessHoursObj = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'BusinessHoursObj'
                    }
                } else if (keyName == "CONFIG-BusinessHours1") {
                    $scope.BusinessHoursObj1 = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'BusinessHoursObj1'
                    }
                } else if (keyName == "CONFIG-BusinessHours2") {
                    $scope.BusinessHoursObj2 = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'BusinessHoursObj2'
                    }
                } else if (keyName == "CONFIG-HUILV") {
                    $scope.huilvs = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'huilvs'
                    }
                } else if (keyName == "CONFIG-PAYQRCODE") {
                    // console.error("1111111111支付二维码", config.value[$scope.store_id]);
                    var zzzz = config.value[$scope.store_id];
                    if (zzzz[0]) {
                        zzzz = {
                            iscode: 0,
                            codeStr: ""
                        };
                    }
                    $scope.shoukuanQrCode = zzzz;
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'shoukuanQrCode'
                    }
                } else if (keyName == "CONFIG-KUAIDIGET") {
                    $scope.kuaidiConfig = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'kuaidiConfig'
                    }
                } else if (keyName == "CONFIG-MINMONEY") {
                    $scope.minMoney = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'minMoney'
                    }
                } else if (keyName == "CONFIG-ADDRESSGPS") {
                    $scope.isAddressGps = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'isAddressGps'
                    }
                } else if (keyName == "CONFIG-PEISONGDATE") {
                    $scope.peisongObj = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'peisongObj'
                    }
                } else if (keyName == "CONFIG-STORECONF") {
                    $scope.storeConf = config.value[$scope.store_id]
                    if (!$scope.storeConf.closeItemLink) {
                        $scope.storeConf.closeItemLink = 0;
                    }
                    if (!$scope.storeConf.closeOrderAdd) {
                        $scope.storeConf.closeOrderAdd = 0;
                    }
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'storeConf'
                    }
                } else if (keyName == "CONFIG-ShowLevelPrice") {
                    $scope.isShowLevelPrice = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'isShowLevelPrice'
                    }
                } else if (keyName == "CONFIG-ORDERXIEYI") {
                    $scope.OrderXieYi = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'OrderXieYi'
                    }
                } else if (keyName == "CONFIG-FENXIAO-FENZHANG") {
                    $scope.fenxiao_fenzhang = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'fenxiao_fenzhang'
                    }
                } else if (keyName == "CONFIG-EXCHANGE") {
                    $scope.exchange = config.value[$scope.store_id];
                    if ($scope.dsaveKey && $scope.dsaveKey[keyName]) {
                        $scope.dsaveKey[keyName].saveObjKey = 'exchange'
                    }
                }
                $scope.config[keyName] = config;
                $scope.autoSave();
                console.error("config", $scope.config);
            });
        };

        $scope.autoSave = function() {
            async.map($scope.dsaveKey, function(autoSaveObj, cb) {
                if (!autoSaveObj.isAdd) {
                    autoSaveObj.isAdd = true;
                    console.error("自动保存", autoSaveObj.keyName);
                    $scope.saveSetDelivery(autoSaveObj.keyName, autoSaveObj.saveObjKey)
                }
            }, function() {
                // $scope.storeXcxConfig();
            })
        }

        $scope.DirectiveCb = function(ruleInfo) {
            if (ruleInfo) {
                $scope.deliveryFee = ruleInfo.freight_rule_id;
                $scope.stepfreightGetOne($scope.deliveryFee);
            }
        };
        $scope.setcallImg = function(attach) {
            if (attach) {
                $scope.shoukuanQrCode.codeStr = attach;
            }
            // console.error("attach",attach);
        };

        $scope.stepfreightGetOne = function(freight_rule_id) {
            var query = {};
            var subquery = {};
            if (!freight_rule_id) {
                $scope.freight_rule = null;
                // console.error("freight_rule_id", freight_rule_id);
                return false;
            }
            subquery.store_id = $scope.store_id;
            subquery.freight_rule_id = freight_rule_id;
            query.query = subquery;

            dataService.stepfreightGet(query).then(function(list) {
                // console.error("查询", list);
                if (list.freight_rule) {
                    $scope.freight_rule = list.freight_rule;
                    $scope.total_count = list.total_count;
                } else {
                    $scope.freight_rule = null;
                }
            });
        };

        $scope.saveSetDelivery = function(keyName, scopeName, value, cb) {

            console.error("value", keyName, scopeName);
            // return false;
            if (value != undefined) {
                $scope.config[keyName].value[$scope.store_id] = value;
            } else {
                if (scopeName == 'userMenuChecked') {
                    var data = [],
                        data1 = [];
                    var isMenuName = false;
                    _.map($scope.userMenuChecked, function(path) {
                        var index = _.findIndex($scope.userMenuBars, {
                            value: path
                        })
                        if (index > -1) {
                            data.push($scope.userMenuBars[index]);
                            data1.push($scope.userMenuBars[index].value);
                            if ($scope.userMenuBars[index].text != $scope.userMenuClone[index].text) {
                                isMenuName = true;
                            }
                        }
                    })
                    console.error("保存", isMenuName);
                    if (isMenuName) {
                        $scope.config[keyName].value[$scope.store_id] = data;
                    } else {
                        $scope.config[keyName].value[$scope.store_id] = data1;
                    }
                } else {
                    $scope.config[keyName].value[$scope.store_id] = $scope[scopeName];
                }
                // console.error("$scope[scopeName]", $scope[scopeName]);
            }
            // console.error("config.", $scope.config, keyName, $scope.huilvs);

            // return false;
            // $scope.config.value=""
            // $scope.config[keyName].value[$scope.store_id]={};
            // return false;
            var method = $scope.config[keyName].wxapp_cfg_id ?
                "wxappUpdate" :
                "wxappAdd";
            dataService[method]($scope.config[keyName]).then(function(result) {
                if (result.app_id) {
                    if ($scope.dsaveKey[keyName] && $scope.dsaveKey[keyName].isAdd) {
                        $scope.storeBaseconfig(keyName)
                        delete $scope.dsaveKey[keyName]
                    } else {
                        helper.myAlert("成功！");
                        $scope.storeXcxConfig();
                    }
                    return true;
                } else {
                    helper.myAlert("出错：" + result.Msg);
                    return false;
                }
            });
        };

        //转发标题设置
        $scope.setZfTtitle = function() {
            var keyName = "ZF_TITLE" + $rootScope.store_id;

            var zf_title = $scope.zf_title;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    a.value = {
                        zf_title: zf_title
                    };
                    dataService.shopConfigUpdate(a).then(function(result) {
                        if (result.shop_config_id) {
                            $scope.zf_title = zf_title;
                            helper.myAlert("success");
                        }
                    });
                } else {
                    dataService
                        .shopConfigAdd({
                            field: keyName,
                            value: {
                                zf_title: zf_title
                            }
                        })
                        .then(function(result) {
                            if (result.shop_config_id) {
                                $scope.zf_title = zf_title;
                                helper.myAlert("success");
                            }
                        });
                }
            });
        };

        $scope.getZfTitle = function() {
            var keyName = "ZF_TITLE" + $rootScope.store_id;
            dataService.shopConfigOneByKey(keyName).then(function(a) {
                if (a) {
                    dataService.shopConfigOne(a.shop_config_id).then(function(result) {
                        if (result.shop_config_id) {
                            var value = JSON.parse(result.value);
                            $scope.zf_title = value.zf_title;
                        } else {
                            $scope.zf_title = "";
                        }
                    });
                } else {
                    $scope.zf_title = "";
                }
            });
        };
        //复制门店信息
        $scope.copyAction = function() {
            $scope.store_id = $location.search().store_id;
            // copystoredata
        };

        // removeDataCache

        $scope.getoldstore = function(store) {
            if (store) {
                $timeout(function() {
                    console.error("store", store, $scope.old_store_id);
                });
                // console.error("store",store,$scope.old_store_id);
                // $scope.old_store_id = store;
            }
        };
        //
        $scope.storecopy = function() {
            // $scope.storeNewcopy();
            if ($scope.store_id == $scope.old_store_id) {
                helper.myAlert("不能选择相同的店铺复制");
                return;
            }
            // if ($scope.new_wxappid == $scope.old_wxappid) {
            //     helper.myAlert("不能选择相同的小程序进行复制");
            //     return;
            // }
            var query = {
                old_store_id: $scope.old_store_id,
                new_store_id: $scope.store_id,
                new_wxappid: $scope.new_wxappid,
                old_wxappid: $scope.old_wxappid,
            };
            dataService.copyStoreData(query).then(function(result) {
                if (result.Msg) {
                    helper.myAlert(result.Msg);
                } else {
                    helper.myAlert("复制数据中！");
                }
            });
        };

        $scope.storeNewcopy = function() {
            var query = {
                old_store_id: "4347",
                new_store_id: $scope.store_id
            };
            dataService.copyStoreData(query).then(function(result) {
                if (result.Msg) {
                    helper.myAlert(result.Msg);
                } else {
                    helper.myAlert("复制数据中！");
                }
            });
        };


        $scope.quickCreateStore = function(store) {
            // console.error("ssss", store);
            if (store && store.config) {
                if (store.is_main != 1) {
                    helper.message("子店无法使用", "error");
                    return;
                }
                var config = JSON.parse(store.config);
                if (config && config.store_apply && config.store_apply.app_id && config.store_apply.role_id) {
                    $scope.openQrcode(ERP_CONFIG.BackAppId);
                } else {
                    helper.message("你先配置子店参数再使用。", "error");
                    gourl("#/store/add?store_id=" + $rootScope.store_id);
                }
            } else {
                helper.message("你先配置子店参数再使用。", "error");
                gourl("#/store/add?store_id=" + $rootScope.store_id);
            }
        }

        $scope.openQrcode = function(app_id) {
            // console.error("222", app_id, $scope.wxqrcodeScene);
            dataService.acodeunlimitGet(
                app_id,
                $scope.wxqrcodeScene,
                true,
                "pages/admin/index/index"
            ).then(function(image) {
                // console.error("二维码数据：", image);
                if (!image) {
                    //$scope.authUrl();
                    helper.myAlert("出错了！");
                    return false;
                }

                $.alert({
                    backdrop: "static",
                    keyboard: false,
                    title: "<span>快速创建门店码</span>",
                    body: '<div style="text-align:center;"><img src="data:image/png;base64,' +
                        image +
                        '"  width="240"/></div>',
                    okBtn: '{{"二维码"|translate}}',
                    closeBtn: true,
                    hasfoot: false,
                    transition: true,
                    width: "small",
                    show: function(e) {},
                    okHide: function(e) {},
                    shown: function(e) {}
                });
            });
        };
        //返回选中角色数据
        $scope.roledata = function(roleInfo) {
            $scope.roleInfo = roleInfo;
            $scope.store.config.store_apply.role_id = $scope.roleInfo.role_id;
        }

        //返回选中用户数据
        $scope.userdata = function(userInfo) {
            $scope.userInfo = userInfo;
            $scope.store.user_id = $scope.userInfo.user_id;
        }


        //快速申请门店列表
        $scope.applylist = function() {
            $scope.applyStatus = {
                0: "未审核",
                1: "通过",
                2: "未通过"
            }
            var data = {
                store_id: $rootScope.store_id
            }
            dataService.applyList(data).then(function(result) {
                if (result.data) {
                    $scope.storeApplyList = result.data;
                }
            })
        }
        $scope.applyupdate = function(data) {
            dataService.applyupdate(data).then(function(result) {
                console.error("result", result);
                if (result.Msg != 'ok') {
                    helper.myAlert(result.Msg);
                } else {
                    helper.myAlert("保存成功");
                    $scope.applyList();
                }
            })
        }
    }
})();